package com.example.nine

import android.graphics.BitmapFactory
import android.graphics.NinePatch
import android.graphics.drawable.NinePatchDrawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.core.graphics.drawable.toDrawable
import androidx.recyclerview.widget.RecyclerView

class ChatAdapter(val data:List<ChatMessage>) : RecyclerView.Adapter<ChatViewHolder>() {

    var bgDrawablePath : (()->String?)? = null
    var useNinePatch : Boolean = true

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChatViewHolder {
        val layoutRes =when(viewType){
            0-> R.layout.item_chat
            1-> R.layout.item_chat_me
            else ->R.layout.item_chat
        }
        return ChatViewHolder(LayoutInflater.from(parent.context).inflate(layoutRes, parent, false))
    }

    override fun getItemViewType(position: Int): Int {
        return if(data[position].ifMe) 1 else 0
    }

    override fun getItemCount(): Int {
        return data.size
    }

    override fun onBindViewHolder(holder: ChatViewHolder, position: Int) {
        val item = data[position]
        holder.content.text = item.message
        loadNineDrawable(holder.content, bgDrawablePath?.invoke(), useNinePatch, item.ifMe )
        if(!item.ifMe){
            holder.name?.text = item.name
        }
    }

    private fun loadNineDrawable(targetView:View, ninePatchName:String?, isUseNinePatch:Boolean, ifMe:Boolean){
        if(ninePatchName==null){
            return
        }
        if(targetView.getTag(R.id.tag_nine_state) == isUseNinePatch && targetView.getTag(R.id.tag_bg_path) == ninePatchName){
            return
        }

        val path = "${ninePatchName}${if(ifMe)"_e" else "_s"}_9.9.png"
        val inputStream = targetView.context.resources.assets.open(path)
        val bitmap = BitmapFactory.decodeStream(inputStream)
        if(isUseNinePatch){
            val chunk = bitmap.ninePatchChunk
            if(NinePatch.isNinePatchChunk(chunk)){
                val drawable = NinePatchDrawable(targetView.resources, bitmap, chunk, NinePatchChunk.getPaddingRect(chunk), "")
                targetView.background = drawable
            }else{
                Toast.makeText(targetView.context, "只能加载.9背景图", Toast.LENGTH_SHORT).show()
            }
        }else{
            targetView.background = bitmap.toDrawable(targetView.resources)
        }
        targetView.setTag(R.id.tag_nine_state, isUseNinePatch)
        targetView.setTag(R.id.tag_bg_path, ninePatchName)
    }

}

class ChatViewHolder(val view: View):RecyclerView.ViewHolder(view){

    val name: TextView?
    val content:TextView

    init {
        name = view.findViewById(R.id.tv_name)
        content = view.findViewById(R.id.tv_content)
    }

}